#!/usr/bin/env node

/**
 * ================================================
 * Builder.Alyr.Net 智能体生成文件 [TRAE-ALYR-FRAMEWORK] [2025-07-29]
 * 修改范围声明：本次仅修改 utils/framework-selector.js
 * (c) 2020-2025 ALYR.NET // 版权不可修改
 * ================================================
 */

const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const readline = require('readline');

class FrameworkSelector {
  constructor() {
    this.extendedConfigPath = path.join(__dirname, '../config/extended-frameworks-config.json');
    this.configSwitchPath = path.join(__dirname, '../config/config-switch-demo.js');
    this.extendedConfig = this.loadExtendedConfig();
    
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
  }

  /**
   * 加载扩展框架配置
   */
  loadExtendedConfig() {
    try {
      return JSON.parse(fs.readFileSync(this.extendedConfigPath, 'utf8'));
    } catch (error) {
      console.log(chalk.red('❌ 无法加载扩展框架配置文件'));
      process.exit(1);
    }
  }

  /**
   * 主菜单
   */
  async showMainMenu() {
    console.log(chalk.cyan('\n🎯 Builder.Alyr.Net 框架选择器 V4.2.3'));
    console.log(chalk.cyan('=================================================='));
    console.log(chalk.yellow('请选择您的需求类型:'));
    console.log('');
    console.log('1. 🏢 企业级应用开发');
    console.log('2. 🚀 创业项目快速开发');
    console.log('3. 📱 跨平台应用开发');
    console.log('4. 🇨🇳 国产生态系统');
    console.log('5. 🌍 国际主流框架');
    console.log('6. 📊 框架对比分析');
    console.log('7. 🔧 配置预设切换');
    console.log('0. 退出');
    console.log('');

    const choice = await this.askQuestion('请输入选项 (0-7): ');
    await this.handleMainMenuChoice(choice);
  }

  /**
   * 处理主菜单选择
   */
  async handleMainMenuChoice(choice) {
    switch (choice) {
      case '1':
        await this.showEnterpriseOptions();
        break;
      case '2':
        await this.showStartupOptions();
        break;
      case '3':
        await this.showCrossPlatformOptions();
        break;
      case '4':
        await this.showChineseEcosystem();
        break;
      case '5':
        await this.showInternationalFrameworks();
        break;
      case '6':
        await this.showFrameworkComparison();
        break;
      case '7':
        await this.showConfigPresets();
        break;
      case '0':
        console.log(chalk.green('👋 感谢使用 Builder.Alyr.Net 框架选择器！'));
        this.rl.close();
        return;
      default:
        console.log(chalk.red('❌ 无效选项，请重新选择'));
        await this.showMainMenu();
    }
  }

  /**
   * 企业级应用选项
   */
  async showEnterpriseOptions() {
    console.log(chalk.cyan('\n🏢 企业级应用开发推荐'));
    console.log(chalk.cyan('=================================================='));
    
    const recommendations = this.extendedConfig.recommendations.enterprise;
    
    console.log(chalk.yellow('前端框架推荐:'));
    Object.entries(recommendations.frontend).forEach(([framework, libs]) => {
      console.log(chalk.white(`  ${framework.toUpperCase()}: ${libs.join(', ')}`));
    });

    console.log(chalk.yellow('\n后端框架推荐:'));
    Object.entries(recommendations.backend).forEach(([language, frameworks]) => {
      console.log(chalk.white(`  ${language.toUpperCase()}: ${frameworks.join(', ')}`));
    });

    console.log(chalk.yellow('\n🎯 推荐组合:'));
    console.log(chalk.green('  1. React + Ant Design + Umi + Spring Boot (Java后端)'));
    console.log(chalk.green('  2. Vue + Element Plus + Midway.js (Node.js全栈)'));
    console.log(chalk.green('  3. Angular + Angular Material + Django (Python后端)'));

    await this.askToContinue();
  }

  /**
   * 创业项目选项
   */
  async showStartupOptions() {
    console.log(chalk.cyan('\n🚀 创业项目快速开发推荐'));
    console.log(chalk.cyan('=================================================='));
    
    const recommendations = this.extendedConfig.recommendations.startup;
    
    console.log(chalk.yellow('全栈框架推荐:'));
    recommendations.fullstack.forEach((framework, index) => {
      console.log(chalk.white(`  ${index + 1}. ${framework}`));
    });

    console.log(chalk.yellow('\n跨平台开发推荐:'));
    recommendations.crossPlatform.forEach((framework, index) => {
      console.log(chalk.white(`  ${index + 1}. ${framework}`));
    });

    console.log(chalk.yellow('\n🎯 推荐理由:'));
    console.log(chalk.green('  ✅ 开发速度快，一套代码多端运行'));
    console.log(chalk.green('  ✅ 学习成本低，社区支持好'));
    console.log(chalk.green('  ✅ 适合MVP快速验证'));

    await this.askToContinue();
  }

  /**
   * 跨平台应用选项
   */
  async showCrossPlatformOptions() {
    console.log(chalk.cyan('\n📱 跨平台应用开发推荐'));
    console.log(chalk.cyan('=================================================='));
    
    const crossPlatform = this.extendedConfig.frameworks.crossPlatform.chinese;
    
    crossPlatform.forEach((framework, index) => {
      console.log(chalk.yellow(`${index + 1}. ${framework.name}`));
      console.log(chalk.white(`   语言: ${framework.language}`));
      console.log(chalk.white(`   公司: ${framework.company}`));
      console.log(chalk.white(`   描述: ${framework.description}`));
      console.log(chalk.white(`   适用: ${framework.useCase}`));
      console.log('');
    });

    console.log(chalk.yellow('🎯 选择建议:'));
    console.log(chalk.green('  uni-app: 适合Vue开发者，DCloud生态完善'));
    console.log(chalk.green('  Taro: 适合React开发者，京东开源，支持鸿蒙'));

    await this.askToContinue();
  }

  /**
   * 国产生态系统
   */
  async showChineseEcosystem() {
    console.log(chalk.cyan('\n🇨🇳 国产生态系统'));
    console.log(chalk.cyan('=================================================='));
    
    const ecosystems = this.extendedConfig.ecosystemMap;
    
    Object.entries(ecosystems).forEach(([company, ecosystem]) => {
      console.log(chalk.yellow(`${company.toUpperCase()} 生态:`));
      if (ecosystem.frontend) {
        console.log(chalk.white(`  前端: ${ecosystem.frontend.join(', ')}`));
      }
      if (ecosystem.backend) {
        console.log(chalk.white(`  后端: ${ecosystem.backend.join(', ')}`));
      }
      if (ecosystem.crossPlatform) {
        console.log(chalk.white(`  跨端: ${ecosystem.crossPlatform.join(', ')}`));
      }
      console.log(chalk.gray(`  ${ecosystem.description}`));
      console.log('');
    });

    await this.askToContinue();
  }

  /**
   * 国际主流框架
   */
  async showInternationalFrameworks() {
    console.log(chalk.cyan('\n🌍 国际主流框架'));
    console.log(chalk.cyan('=================================================='));
    
    const international = this.extendedConfig.frameworks;
    
    console.log(chalk.yellow('前端框架:'));
    international.frontend.international.forEach((framework, index) => {
      console.log(chalk.white(`  ${index + 1}. ${framework.name} (${framework.company})`));
      console.log(chalk.gray(`     ${framework.description}`));
    });

    console.log(chalk.yellow('\n后端框架:'));
    international.backend.international.forEach((framework, index) => {
      console.log(chalk.white(`  ${index + 1}. ${framework.name} (${framework.language})`));
      console.log(chalk.gray(`     ${framework.description}`));
    });

    console.log(chalk.yellow('\n全栈框架:'));
    international.fullstack.international.forEach((framework, index) => {
      console.log(chalk.white(`  ${index + 1}. ${framework.name} (${framework.company})`));
      console.log(chalk.gray(`     ${framework.description}`));
    });

    await this.askToContinue();
  }

  /**
   * 框架对比分析
   */
  async showFrameworkComparison() {
    console.log(chalk.cyan('\n📊 框架对比分析'));
    console.log(chalk.cyan('=================================================='));
    
    console.log(chalk.yellow('前端框架对比:'));
    console.log('┌─────────────┬──────────────┬──────────────┬──────────────┐');
    console.log('│    框架     │    学习曲线   │    生态完善度 │    企业采用度 │');
    console.log('├─────────────┼──────────────┼──────────────┼──────────────┤');
    console.log('│    React    │      中等     │      ★★★★★   │      ★★★★★   │');
    console.log('│    Vue      │      简单     │      ★★★★☆   │      ★★★★☆   │');
    console.log('│   Angular   │      困难     │      ★★★★☆   │      ★★★☆☆   │');
    console.log('│   Svelte    │      简单     │      ★★☆☆☆   │      ★★☆☆☆   │');
    console.log('└─────────────┴──────────────┴──────────────┴──────────────┘');

    console.log(chalk.yellow('\n国产UI库对比:'));
    console.log('┌─────────────┬──────────────┬──────────────┬──────────────┐');
    console.log('│    UI库     │    设计风格   │    组件丰富度 │    文档质量   │');
    console.log('├─────────────┼──────────────┼──────────────┼──────────────┤');
    console.log('│ Ant Design  │   企业级简洁  │      ★★★★★   │      ★★★★★   │');
    console.log('│  TDesign    │   现代化清新  │      ★★★★☆   │      ★★★★☆   │');
    console.log('│ Arco Design │   简约现代    │      ★★★★☆   │      ★★★★☆   │');
    console.log('│ Element Plus│   简洁实用    │      ★★★★☆   │      ★★★★☆   │');
    console.log('└─────────────┴──────────────┴──────────────┴──────────────┘');

    await this.askToContinue();
  }

  /**
   * 配置预设切换
   */
  async showConfigPresets() {
    console.log(chalk.cyan('\n🔧 配置预设切换'));
    console.log(chalk.cyan('=================================================='));
    
    console.log(chalk.yellow('可用的配置预设:'));
    console.log('1. react-enterprise - React企业级开发');
    console.log('2. vue-modern - Vue现代化开发');
    console.log('3. angular-enterprise - Angular企业级开发');
    console.log('4. fullstack-node - Node.js全栈开发');
    console.log('5. alibaba-ecosystem - 阿里系生态开发');
    console.log('6. tencent-ecosystem - 腾讯系生态开发');
    console.log('7. bytedance-ecosystem - 字节系生态开发');
    console.log('8. cross-platform-uniapp - uni-app跨端开发');
    console.log('9. cross-platform-taro - Taro跨端开发');
    console.log('');

    const choice = await this.askQuestion('请选择要切换的配置 (1-9) 或按回车返回主菜单: ');
    
    if (choice && choice >= '1' && choice <= '9') {
      const presets = [
        'react-enterprise', 'vue-modern', 'angular-enterprise', 'fullstack-node',
        'alibaba-ecosystem', 'tencent-ecosystem', 'bytedance-ecosystem',
        'cross-platform-uniapp', 'cross-platform-taro'
      ];
      
      const selectedPreset = presets[parseInt(choice) - 1];
      console.log(chalk.green(`\n🔄 正在切换到配置: ${selectedPreset}`));
      
      try {
        const { execSync } = require('child_process');
        execSync(`node ${this.configSwitchPath} switch ${selectedPreset}`, { stdio: 'inherit' });
        console.log(chalk.green('✅ 配置切换完成！'));
      } catch (error) {
        console.log(chalk.red('❌ 配置切换失败'));
      }
    }

    await this.askToContinue();
  }

  /**
   * 询问问题
   */
  askQuestion(question) {
    return new Promise((resolve) => {
      this.rl.question(question, (answer) => {
        resolve(answer.trim());
      });
    });
  }

  /**
   * 询问是否继续
   */
  async askToContinue() {
    console.log('');
    await this.askQuestion('按回车键返回主菜单...');
    await this.showMainMenu();
  }

  /**
   * 启动选择器
   */
  async start() {
    await this.showMainMenu();
  }
}

// 如果直接运行此文件
if (require.main === module) {
  const selector = new FrameworkSelector();
  selector.start().catch(console.error);
}

module.exports = FrameworkSelector;